<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexFreightTemplateRequest;
use App\Http\Requests\StoreFreightTemplateRequest;
use App\Http\Requests\UpdateFreightTemplateRequest;
use App\Http\Resources\FreightTemplateResource;
use App\Models\FreightTemplate;
use App\Models\FreightTemplateKey;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class FreightTemplateController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexFreightTemplateRequest $request)
    {
        $query = FreightTemplate::query();
        if (!isSuperadmin()) {
            $query->where('admin_id', Auth::id());
        }
        $query->when($request->filled('name'), function ($query) use ($request) {
            $name = $request->input('name');
            return $query->where('name', 'like', "%$name%");
        });

        $data = $query->with(['freights', 'admins'])->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response =  FreightTemplateResource::collection($data);
        $total = $response->total();
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreFreightTemplateRequest $request)
    {
        // 开启事务
        DB::beginTransaction();
        $freighttemplate = new FreightTemplate();
        try {
            $freighttemplate->fill($request->input());
            $freighttemplate->admin_id = Auth::id();
            $freighttemplate->save();
            // 如果请求中包含 freight_template_keys 数据
            if ($request->filled('freights')) {
                foreach ($request->input('freights') as $keyValue) {
                    $freighttemplateKey = new FreightTemplateKey();
                    $freighttemplateKey->region_freight = $keyValue['region_freight'];
                    $freighttemplateKey->region = $keyValue['region'];
                    // 关联 freight_template_keys 表
                    $freighttemplateKey->freight_id = $freighttemplate->id;
                    $freighttemplateKey->save();
                }
            }
            // 提交事务
            DB::commit();

            return $this->success('添加成功', $freighttemplate);
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            DB::rollback();
            return $this->error('添加失败', $e);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(FreightTemplate $freightTemplate, $id)
    {
        $freightTemplate = $freightTemplate->findOrFail($id);
        $this->authorize('viewAny', $freightTemplate);
        $response =  new FreightTemplateResource($freightTemplate->load(['freights', 'admins']));
        return $this->success('查询成功', $response);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(FreightTemplate $freightTemplate)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateFreightTemplateRequest $request, FreightTemplate $freightTemplate, $id)
    {
        $freightTemplate = $freightTemplate->findOrFail($id);
        $this->authorize('update', $freightTemplate);
        // 开启事务
        DB::beginTransaction();
        try {
            $freightTemplate->fill($request->input());
            $freightTemplate->admin_id = Auth::id();
            $freightTemplate->save();
            // 如果请求中包含 freight_template_keys 数据
            if ($request->filled('freights')) {
                $freightTemplate->freights()->delete();
                
                foreach ($request->input('freights') as $keyValue) {
                    $freighttemplateKey = new FreightTemplateKey();

                    $freighttemplateKey->region_freight = $keyValue['region_freight'];
                    $freighttemplateKey->region = $keyValue['region'];
                    // 关联 freight_template_keys 表
                    $freighttemplateKey->freight_id = $freightTemplate->id;
                    $freighttemplateKey->save();
                }
            }
            // 提交事务
            DB::commit();

            return $this->success('更新成功', $freightTemplate);
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            DB::rollback();
            return $this->error('更新失败', $e);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(FreightTemplate $freightTemplate, $id)
    {
        $freightTemplate = $freightTemplate->findOrFail($id);
        $this->authorize('delete', $freightTemplate);

        // 开启事务
        DB::beginTransaction();

        try {
            // 删除与当前 freightTemplate 记录相关联的 freightTemplate 记录
            $freightTemplate->freights()->delete();
            // 删除 norms 记录
            $freightTemplate->delete();
            // 提交事务
            DB::commit();

            return $this->success('删除成功');
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            DB::rollback();
            return $this->error('删除失败');
        }
    }
}
